package comxyp.controller.workbench;
import com.github.pagehelper.PageInfo;
import comxyp.common.Constant;
import comxyp.common.ReturnData;
import comxyp.pojo.workbench.Activity;
import comxyp.service.page.PageService;
import comxyp.service.workbench.ActivityService;
import comxyp.utils.DateUtils;
import comxyp.utils.HSSFUtils;
import comxyp.utils.UUIDUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/workbench")
public class ActivityController {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private PageService pageService;
    ReturnData returnData = new ReturnData();
    @RequestMapping("/saveActivity")
    @ResponseBody
    public Object saveActivity(Activity activity){
        activity.setCreateTime(DateUtils.formateDateTime(new Date()));
        activity.setId((int)(Math.random()*100)+(int)(Math.random()*20)+"");
        //调用service层方法，保存创建的市场活动
        int n = activityService.saveActivity(activity);
        if(n>0){
            returnData.setCode(Constant.status2);
            returnData.setMsg("保存成功");
        } else {
            returnData.setCode(Constant.status1);
            returnData.setMsg("保存失败");
        }

        return returnData;
    }
    @RequestMapping("/findAll")
    @ResponseBody
    public ModelAndView findAll(@RequestParam(defaultValue = "1") int page,String name,String owner){
        ModelAndView modelAndView = new ModelAndView();
        PageInfo<Activity> pageInfo = pageService.splitPage(page,5);
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.setViewName("workbench/activity/index");
        return modelAndView;
    }
    @RequestMapping("/findByName")
    @ResponseBody
    public List findByName(String name, String owner){
        List<Activity> activityList = activityService.selectByName(name,owner);
        return activityList;
    }
    //单个删除
    @RequestMapping("/deleteById")
    @ResponseBody
    public Object deleteById(@RequestParam String id){
        int n = activityService.deleteById(id);
        if(n>0){
            returnData.setCode(Constant.status2);
            returnData.setMsg("删除成功");
        } else {
            returnData.setCode(Constant.status1);
            returnData.setMsg("删除失败");
        }
        return returnData;
    }
    //批量删除
    @RequestMapping("/deleteByIdAll")
    @ResponseBody
    public Object deleteByIdAll(String[] id){
        int n = activityService.deleteByIdAll(id);
        if(n>0){
                returnData.setCode(Constant.status2);
                returnData.setMsg("批量删除成功");
        }else {
            returnData.setCode(Constant.status1);
            returnData.setMsg("批量删除失败");
        }
        return returnData;
    }
    //信息回显
    @RequestMapping("/updateByIds")
    @ResponseBody
    public Activity updateByIds(String id){
        Activity activityList = activityService.selectById(id);
        return activityList;
    }
    //信息回显
    @RequestMapping("/updateById")
    @ResponseBody
    public void updateById(String id){
        ModelAndView modelAndView= new ModelAndView();
        Activity activityList = activityService.selectById(id);
        modelAndView.addObject("activityList",activityList);


    }
    //商品更新
    @RequestMapping("/update")
    @ResponseBody
    public Object update(Activity activity){
        activity.setEditTime(DateUtils.formateDateTime(new Date()));
        int n = activityService.updateByPrimaryKeySelective(activity);
        if(n>0){
            returnData.setCode(Constant.status2);
            returnData.setMsg("修改成功");
        }else {
            returnData.setCode(Constant.status1);
            returnData.setMsg("修改失败");
        }
        return returnData;
    }
    //文件下载
    @RequestMapping("/fileDownload")
    public void fileDownload(HttpServletResponse response) throws IOException {
        //设置响应类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //获取输出流
        OutputStream out = response.getOutputStream();
        //浏览器接收到相应信息之后 默认情况下 直接在显示窗口中打开响应信息，即使打不开 只有实在打不开，才会激活文件
        //可以设置响应头信息 使浏览器接收到响应信息之后 直接激活文件下载窗口 即使能打开 也可以吧打开
        response.addHeader("Content-Disposition","attachment;filename =my.xls");
        //读取excel文件 ，把它输出到浏览器
        //我们把磁盘上的文件 输出到浏览器 然后在浏览器上进行下载
        InputStream in = new FileInputStream("E:\\javaWeb项目\\ssm+商城项目\\ssm-shop\\s.xls");
        byte[] buff = new byte[256];
        int len = 0 ;
        while ((len=in.read(buff)) !=-1){
            out.write(buff,0,len);
        }
        //释放资源
        in.close();
        out.flush();
    }
    //文件批量导出
    @RequestMapping("/exportAllActivity")
    public void exportAllActivity(HttpServletResponse response) throws IOException, CloneNotSupportedException {
        List<Activity> activityList = activityService.findAll();
        //创建excel文件 并且把activityList写入到excel文件中
        HSSFWorkbook work = new HSSFWorkbook();
        HSSFSheet sheet = work.createSheet("市场活动列表");
                       HSSFRow row = sheet.createRow(0);
        //每一列对应数据库中的列
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell=row.createCell(1);
        cell.setCellValue("所有者");
        cell=row.createCell(2);
        cell.setCellValue("名称");
        cell=row.createCell(3);
        cell.setCellValue("开始日期");
        cell=row.createCell(4);
        cell.setCellValue("结束日期");
        cell=row.createCell(5);
        cell.setCellValue("成本");
        cell=row.createCell(6);
        cell.setCellValue("描述");
        cell=row.createCell(7);
        cell.setCellValue("创建时间");
        cell=row.createCell(8);
        cell.setCellValue("创建者");
        cell=row.createCell(9);
        cell.setCellValue("修改时间");
        cell=row.createCell(10);
        cell.setCellValue("修改者");
        //遍历activityList  创建HSSFRow 对象 生成所有的数据行
        if(activityList!=null && activityList.size()>0){
            Activity activity = null;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                //每遍历出一个activity  生成一行
                row = sheet.createRow(i+1);
                //每一行创建11列 每一 列的数据从activity中获取
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell=row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell=row.createCell(2);
                cell.setCellValue(activity.getName());
                cell=row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell=row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell=row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell=row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell=row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell=row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell=row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell=row.createCell(10);
                cell.setCellValue(activity.getEditBy());

            }
        }
        //根据work对象 生成excel文件
        /*OutputStream os = new FileOutputStream("E:\\javaWeb项目\\ssm+商城项目\\ssm-shop\\activityList.xls");
        work.write(os);
         //关闭资源
         os.close();*/

         //把生成的excel文件下载到客户端
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        //浏览器接收到相应信息之后 默认情况下 直接在显示窗口中打开响应信息，即使打不开 只有实在打不开，才会激活文件
        //可以设置响应头信息 使浏览器接收到响应信息之后 直接激活文件下载窗口 即使能打开 也可以吧打开
        response.addHeader("Content-Disposition","attachment;filename =activityList.xls");
       /* InputStream in = new FileInputStream("E:\\javaWeb项目\\ssm+商城项目\\ssm-shop\\activityList.xls");
        byte[] buff = new byte[256];
        int len = 0;
        while ((len=in.read(buff))!=-1){
            out.write(buff,0,len);
        }*/
        //从内存中读取数据
        work.write(out);
        out.close();
        out.flush();
    }
    //文件批量选择导出
    @RequestMapping("/findById")
    public void findById(String[] id,HttpServletResponse response) throws IOException, CloneNotSupportedException {
        System.out.println(id);
        List<Activity> activityList = activityService.findById(id);
        //创建excel文件 并且把activityList写入到excel文件中
        HSSFWorkbook work = new HSSFWorkbook();
        HSSFSheet sheet = work.createSheet("市场活动列表");
        HSSFRow row = sheet.createRow(0);
        //每一列对应数据库中的列
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell=row.createCell(1);
        cell.setCellValue("所有者");
        cell=row.createCell(2);
        cell.setCellValue("名称");
        cell=row.createCell(3);
        cell.setCellValue("开始日期");
        cell=row.createCell(4);
        cell.setCellValue("结束日期");
        cell=row.createCell(5);
        cell.setCellValue("成本");
        cell=row.createCell(6);
        cell.setCellValue("描述");
        cell=row.createCell(7);
        cell.setCellValue("创建时间");
        cell=row.createCell(8);
        cell.setCellValue("创建者");
        cell=row.createCell(9);
        cell.setCellValue("修改时间");
        cell=row.createCell(10);
        cell.setCellValue("修改者");
        //遍历activityList  创建HSSFRow 对象 生成所有的数据行
        if(activityList!=null && activityList.size()>0){
            Activity activity = null;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                //每遍历出一个activity  生成一行
                row = sheet.createRow(i+1);
                //每一行创建11列 每一 列的数据从activity中获取
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell=row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell=row.createCell(2);
                cell.setCellValue(activity.getName());
                cell=row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell=row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell=row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell=row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell=row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell=row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell=row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell=row.createCell(10);
                cell.setCellValue(activity.getEditBy());

            }
        }

        //把生成的excel文件下载到客户端
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        //浏览器接收到相应信息之后 默认情况下 直接在显示窗口中打开响应信息，即使打不开 只有实在打不开，才会激活文件
        //可以设置响应头信息 使浏览器接收到响应信息之后 直接激活文件下载窗口 即使能打开 也可以吧打开
        response.addHeader("Content-Disposition","attachment;filename =activityList.xls");
        //从内存中读取数据
        work.write(out);
        out.close();
        out.flush();
    }
    //我们要去springMvc.xml中进行配置文件上传解析器
    //文件上传
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Object fileUpload(String username, MultipartFile myFile) throws IOException {
        System.out.println(username);
        //把文件在服务指定的目录中生成一个同样的文件
        //获取上传文件名
        String originalFilename = myFile.getOriginalFilename();
        File file = new File("E:\\javaWeb全家桶\\ssm-crm\\",originalFilename);
        myFile.transferTo(file);

        //返回响应信息
        ReturnData returnData = new ReturnData();
        returnData.setCode(Constant.status1);
        returnData.setMsg("上传文件成功");
        return  returnData;
    }
    //文件批量上传
    @RequestMapping("/importActivityAll")
    public Object  importActivityAll(MultipartFile multipartFile) throws IOException {
        ReturnData returnData = new ReturnData();
        //先获取上传的文件名
        //String fileName = multipartFile.getOriginalFilename();
        //把excel文件写到磁盘目录中
       /* File file = new File("E:\\javaWeb全家桶\\ssm-crm\\file\\",fileName);
        multipartFile.transferTo(file);*/
        //根据excel文件 获取文件中的数据 并且封装成activityList
        //根据excel文件生成HSSFWorkbook对象 封装了excel文件的所有信息
       /* InputStream is=new FileInputStream("E:\\javaWeb全家桶\\ssm-crm\\file\\"+fileName);
        HSSFWorkbook wb=new HSSFWorkbook(is);*/
        InputStream is  = multipartFile.getInputStream();
        HSSFWorkbook wb = new HSSFWorkbook(is);
        //根据wb获取HSSFSheet对象，封装了一页的所有信息
        HSSFSheet sheet=wb.getSheetAt(0);//页的下标，下标从0开始，依次增加
        //根据sheet获取HSSFRow对象，封装了一行的所有信息
        HSSFRow row=null;
        HSSFCell cell=null;
        Activity activity = null;
        List<Activity> activityList = new ArrayList<>();
        //数据从第二行开始
        for(int i=1;i<=sheet.getLastRowNum();i++) {//sheet.getLastRowNum()：最后一行的下标
            row=sheet.getRow(i);//行的下标，下标从0开始，依次增加
            activity = new Activity();
            //封装了一个工具获取id值
            activity.setId((int)(Math.random()*10000)+(int)(Math.random()*10000)+"");
            activity.setCreateTime(DateUtils.formateDateTime(new Date()));
            for(int j=0;j<row.getLastCellNum();j++) {//row.getLastCellNum():最后一列的下标+1
                //根据row获取HSSFCell对象，封装了一列的所有信息
                cell=row.getCell(j);//列的下标，下标从0开始，依次增加
                //获取列中的数据
                String  cellValue = HSSFUtils.getCellValueForStr(cell);
                //因为id不用用户输入 所有从第一行开始的是所有者
                if(j==0){
                    activity.setOwner(cellValue);
                } else if(j ==1){
                    activity.setName(cellValue);
                } else if(j==2){
                    activity.setStartDate(cellValue);
                } else if(j==3){
                    activity.setEndDate(cellValue);
                } else if(j==4){
                    activity.setCost(cellValue);
                }
                else if(j==5){
                    activity.setDescription(cellValue);
                }
            }

            //每一行中所有列都封装完成之后 把activity保存到list中
            activityList.add(activity);
        }
        //调用service中方法
        int n = activityService.insertActivityByList(activityList);
        if(n>0){
            returnData.setCode(Constant.status2);
            returnData.setMsg("批量导入成功");
        } else{
            returnData.setCode(Constant.status1);
            returnData.setMsg("批量导入失败");
        }
        return returnData;
    }
    //查看详情页
    @RequestMapping("/detailShow")
    public ModelAndView detailShow(String id){
        ModelAndView modelAndView = new ModelAndView();
        Activity activity = activityService.selectById(id);
        modelAndView.addObject("activity",activity);
        modelAndView.setViewName("workbench/activity/detail");
        return modelAndView;
    }
}
